import React from 'react';
import {injectIntl, formatMessage} from './intl';
import PropTypes from 'prop-types';
import {Form, Button, Spin, Divider, Card, Row, Col, Tabs, message, Modal, Alert} from 'antd';
import routes from './routes';
import {FORM_OPTIONS, FORM_ROW_OPTIONS, PAGE} from '../constants';
import {conventEnumValueToString} from '../utils';
import {PERMISSION} from './constants';
import TextInput from 'Shared/components/TextInput';
import WrappedDatePicker from '../common/WrappedDatePicker';
import WrappedSelect from '../common/WrappedSelect';
import {validateAdd} from './utils';
import Return from '../common/Return';
import {warrantyPolicyType, dealerType} from '../Enum';
const FormItem = Form.Item;
const autosize = {minRows: 1};
const EMPTY_ARRAY = [];
const EMPTY_OBJECT = {};
const TabPane = Tabs.TabPane;
import AddDetail from './AddDetail';
import AddVehicle from './AddVehicle';
import AddCategory from './AddCategory';
import DetailSelectPanel from './DetailSelectPanel';
import DealerSelectPanel from '../common/DealerSelect/SelectEdit';
import styles from './style.css';
const defaultCollapseKey = ['1'];
export const dealerConditions = {
    type: dealerType.总代
};
export class Add extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        isValidate: false,
        showPanel: false,
        closable: false
    };

    componentDidMount() {
        this.props.init();
        this.ismounted = true;
    }

    componentWillUnmount() {
        this.ismounted = false;
        this.props.onUmount();
    }

    handleFilterChange = (value, name) => {
        if(!this.state.hasOperat)
            this.setState({
                hasOperat: true
            });
        this.props.onConditionsChange(name, value);
    };

    showPanel = () => {
        this.setState({
            showPanel: !this.state.showPanel
        });
    }
    afterSelect = id => {
        if(!this.state.hasOperat)
            this.setState({
                hasOperat: true
            });
        if(id)
            return this.setState({
                showPanel: false,
                detailId: id
            });
        return this.setState({
            showPanel: false
        });
    }

    onChangeCollapse = key => {
        if(!this.state.hasOperat)
            this.setState({
                hasOperat: true
            });
        this.setState({
            itemId: key
        });
    }

    onChangeDetailCollapse = key => {
        if(!this.state.hasOperat)
            this.setState({
                hasOperat: true
            });
        this.setState({
            detailCollapse: key
        });
    }

    onSubmit = () => {
        const result = validateAdd(this.props.conditions, this.props.id);
        if(result) {
            this.setState({
                isValidate: true,
                detailId: result.detailId,
                itemId: result.itemId,
                detailCollapse: defaultCollapseKey
            });
            return message.warn(result.message);
        }
        this.setState({
            loading: true
        });
        this.props.onSubmit().then(success => {
            if(this.ismounted && !success)
                this.setState({
                    loading: false
                });
        });
    };

    onChangeDetailInfo = (name, value) => {
        const {details = []} = this.props.conditions;
        if(!this.state.hasOperat)
            this.setState({
                hasOperat: true
            });
        this.props.onDetailChange(name, value, this.state.detailId || details[0].id);
    }

    onChangeTabs = id => {
        this.setState({detailId: id});
    }

    onColseTab = targetKey => {
        if(!this.state.hasOperat)
            this.setState({
                hasOperat: true
            });
        this.props.onColseTab(targetKey);
        const {details = []} = this.props.conditions;
        const nextDetailid = details.length > 1 ? details[1].id : '';
        const detailId = details[0].id === targetKey ? nextDetailid : details[0].id;
        this.setState({detailId});
    }

    onClickDeleteDetail = () => {
        this.setState({
            closable: !this.state.closable
        });
    }

    onClickAddDetail = () => {
        if(!this.props.conditions.dealerId)
            return message.warn(this.props.intl.formatMessage({
                id: 'add.onClickAddDetail.message',
                defaultMessage: '请先选择总代'
            }));
        if(!this.state.hasOperat)
            this.setState({
                hasOperat: true
            });
        this.props.onClickAddDetail().then(id => {
            this.setState({detailId: id});
        });
    }

    onSelectDealer = data => {
        if(!this.state.hasOperat)
            this.setState({
                hasOperat: true
            });
        this.props.onSelectDealer(data);
    };
    render() {
        const {details = []} = this.props.conditions;
        const detailOrder = (details.length && this.state.detailId
            ? details.find(item => item.id === this.state.detailId)
            : details[0]) || EMPTY_OBJECT;
        const tabs = details.map(item => <TabPane closable={this.state.closable} tab={item.tabName} key={item.id}>
            <AddDetail isValidate={this.state.isValidate} onChange={this.onChangeDetailInfo} data={detailOrder} />
            {item.type ? <React.Fragment>
                <Divider />
                {item.type === warrantyPolicyType.标准
                    ? <AddCategory
                        isValidate={this.state.isValidate}
                        onChangeCollapse={this.onChangeCollapse}
                        onChangeDetailCollapse={this.onChangeDetailCollapse}
                        itemId={this.state.itemId}
                        detailCollapse={this.state.detailCollapse}
                        data={detailOrder}
                        dealerId={this.props.conditions.dealerId} />
                    : <AddVehicle
                        isValidate={this.state.isValidate}
                        onChangeCollapse={this.onChangeCollapse}
                        onChangeDetailCollapse={this.onChangeDetailCollapse}
                        itemId={this.state.itemId}
                        detailCollapse={this.state.detailCollapse}
                        data={detailOrder} />}
            </React.Fragment> : null}
        </TabPane>);
        const defaultTabKey = details.length ? details[0].id : '';
        const alertMessage = (
            <Row>
                <Col span={18}>{this.props.intl.formatMessage({
                    id: 'add.alert.message',
                    defaultMessage: '点击标签页右侧图标可删除该条款，删除后无法撤销'
                })}</Col>
                <Col span={6} className="col-align-right">
                    <a onClick={this.onClickDeleteDetail}>{this.props.intl.formatMessage({
                        id: 'add.btn.return',
                        defaultMessage: '退出'
                    })}</a>
                </Col>
            </Row>);
        const dealerInfo = this.props.conditions.dealerId ? {
            id: this.props.conditions.dealerId,
            code: this.props.conditions.dealerCode,
            name: this.props.conditions.dealerName
        } : null;
        return (
            <div className={styles.detail}>
                <Modal
                    title={this.props.intl.formatMessage({
                        id: 'add.detail.modal.title',
                        defaultMessage: '备件索赔条款查询'
                    })}
                    width="80%"
                    maskClosable={false}
                    footer={null}
                    wrapClassName={styles.dataSelectModal}
                    destroyOnClose={true}
                    visible={this.state.showPanel}
                    onCancel={this.showPanel}>
                    <DetailSelectPanel onSelect={this.props.onClickCopyDetail} afterSelect={this.afterSelect} />
                </Modal>
                <Spin spinning={this.props.loading || this.state.loading}>
                    <Form className="form-standard">
                        <Card
                            title={this.props.intl.formatMessage({
                                id: 'add.order.title',
                                defaultMessage: '政策信息'
                            })}>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={this.props.intl.formatMessage({
                                        id: 'add.form.brandId',
                                        defaultMessage: '品牌'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={!this.props.id && this.state.isValidate && !this.props.conditions.brandId ? 'error' : null}
                                    required>
                                        {this.props.id
                                            ? <span className="value-font">{`(${this.props.conditions.brandCode})${this.props.conditions.brandName}`}</span>
                                            : <WrappedSelect
                                                name="brandId"
                                                value={this.props.conditions.brandId}
                                                options={this.props.brands}
                                                onChange={this.handleFilterChange} />}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        validateStatus={this.state.isValidate && !this.props.conditions.dealerId ? 'error' : null}
                                        required={!this.props.id}
                                        label={this.props.intl.formatMessage({
                                            id: 'queryPanel.form.dealerId',
                                            defaultMessage: '总代'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {this.props.id ? <span className="value-font">{`(${this.props.conditions.dealerCode})${this.props.conditions.dealerName}`}</span>
                                            : <DealerSelectPanel
                                                allowClear={false}
                                                value={dealerInfo}
                                                conditions={dealerConditions}
                                                onSelect={this.onSelectDealer} />}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={this.props.intl.formatMessage({
                                        id: 'add.form.code',
                                        defaultMessage: '编号'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={this.state.isValidate && !this.props.conditions.code ? 'error' : null}
                                    required>
                                        {this.props.id
                                            ? <span className="value-font">{this.props.conditions.code}</span>
                                            : <TextInput
                                                name="code"
                                                value={this.props.conditions.code}
                                                onBlur={this.handleFilterChange} />}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={this.props.intl.formatMessage({
                                        id: 'add.form.name',
                                        defaultMessage: '名称'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={this.state.isValidate && !this.props.conditions.name ? 'error' : null}
                                    required>
                                        <TextInput
                                            name="name"
                                            value={this.props.conditions.name}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.startDate',
                                            defaultMessage: '启用日期'
                                        })}
                                        {...FORM_OPTIONS.item}
                                        validateStatus={this.state.isValidate && !this.props.conditions.startDate ? 'error' : null}
                                        required>
                                        <WrappedDatePicker
                                            name="startDate"
                                            value={this.props.conditions.startDate}
                                            onChange={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <FormItem
                                    label={this.props.intl.formatMessage({
                                        id: 'add.form.remark',
                                        defaultMessage: '备注'
                                    })}
                                    {...FORM_ROW_OPTIONS.item}>
                                    <TextInput type="textarea" name="remark" autosize={autosize}
                                        value={this.props.conditions.remark} onBlur={this.handleFilterChange} />
                                </FormItem>
                            </Row>
                        </Card>
                        <Card
                            extra={<React.Fragment>
                                <Button size="small" onClick={this.onClickAddDetail}>{this.props.intl.formatMessage({
                                    id: 'add.detail.btn.add',
                                    defaultMessage: '新增'
                                })}</Button>
                                <Button size="small" onClick={this.showPanel}>{this.props.intl.formatMessage({
                                    id: 'add.detail.btn.copy',
                                    defaultMessage: '复制'
                                })}</Button>
                                <Button size="small" disabled={this.state.closable || !details.length}
                                    onClick={this.onClickDeleteDetail}>{this.props.intl.formatMessage({
                                        id: 'add.detail.btn.delete',
                                        defaultMessage: '删除'
                                    })}</Button>
                            </React.Fragment>}
                            title={this.props.intl.formatMessage({
                                id: 'add.detail.title',
                                defaultMessage: '条款信息'
                            })}>
                            {this.state.closable && <Alert className={styles.alertMargin} type="warning" message={alertMessage} showIcon />}
                            <Tabs
                                hideAdd type="editable-card"
                                activeKey={this.state.detailId || defaultTabKey} onChange={this.onChangeTabs} onEdit={this.onColseTab}>
                                {tabs}
                            </Tabs>
                        </Card>
                        {this.props.submitable && (
                            <Card type="inner" className={styles.noMarginTop}>
                                <Row>
                                    <Col className="col-align-right">
                                        <Button
                                            key="audit"
                                            loading={this.state.loading}
                                            onClick={this.onSubmit}
                                            type="primary">
                                            {this.props.intl.formatMessage({
                                                id: 'add.btn.submit',
                                                defaultMessage: '保存'
                                            })}
                                        </Button>
                                    </Col>
                                </Row>
                            </Card>
                        )}
                    </Form>
                </Spin>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        showWarning={this.state.hasOperat}
                        onConfirm={this.props.onCancel} />
                </div>
            </div>
        );
    }
}
Add.propTypes = {
    conditions: PropTypes.object.isRequired,
    init: PropTypes.func.isRequired,
    loading: PropTypes.bool.isRequired,
    submitable: PropTypes.bool.isRequired,
    onCancel: PropTypes.func.isRequired,
    onClickAddDetail: PropTypes.func.isRequired,
    onClickCopyDetail: PropTypes.func.isRequired,
    onColseTab: PropTypes.func.isRequired,
    onConditionsChange: PropTypes.func.isRequired,
    onSubmit: PropTypes.func.isRequired,
    onUmount: PropTypes.func.isRequired,
    id: PropTypes.string,
    intl: PropTypes.object
};
import {connect} from 'react-redux';
import {
    saveSubmitCondition,
    saveDetailCondition,
    clearData,
    tableSearch,
    onSubmit,
    getOrderDetail,
    onClickCopyDetail,
    onClickAddDetail,
    deleteDetail,
    getEditInit,
    selectData,
} from './actions';
import {createSelector} from 'reselect';

import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
const getCondition = selectorFactory(['page', 'appState', 'submitData']);
const getSubmitData = createSelector(
    state => getCondition(state),
    data => {
        const {details = []} = data;
        const indexObj = {};
        for(let i = 0; i < details.length; i++) {
            const item = details[i];
            if(!item.type) {
                item.tabName = formatMessage({
                    id: 'add.type.add',
                    defaultMessage: '新增'
                });
                continue;
            }

            if(indexObj[item.type])
                indexObj[item.type] += 1;
            else
                indexObj[item.type] = 1;
            item.tabName = `${conventEnumValueToString(warrantyPolicyType, item.type)}${indexObj[item.type]}`;
        }
        return data;
    }
);

const getPermissions = createSelector(
    state => state.getIn(['page', 'domainData', 'permission', 'data']),
    (state, ownProps) => ownProps.id,
    state => state.getIn(['page', 'domainData', 'orderDetail', 'data']),
    (permissions, id, detail) => {
        const {options = EMPTY_ARRAY} = detail.toJS();
        const data = permissions.toJS();
        const submitable = id ? data.includes(PERMISSION.update) && options.includes(PERMISSION.update)
            : data.includes(PERMISSION.add);
        return submitable;
    }
);

const getBrands = createSelector(
    state => state.getIn(['page', 'domainData', 'brands', 'data']),
    brands => {
        const data = brands.toJS() || EMPTY_ARRAY;
        return data.map(item => ({
            value: item.id,
            text: `(${item.code})${item.name}`
        }));
    }
);
const mapStateToProps = (state, ownProps) => ({
    id: ownProps.id,
    submitable: getPermissions(state, ownProps),
    loading: state.getIn(['page', 'domainData', 'orderDetail', 'isFetching']),
    conditions: getSubmitData(state),
    brands: getBrands(state)
});

const mapDispatchToProps = (dispatch, ownProps) => ({
    init: () => dispatch(getEditInit(ownProps.id)),
    onConditionsChange: (name, value) => dispatch(saveSubmitCondition(name, value)),
    onDetailChange: (name, value, detailId) => dispatch(saveDetailCondition(name, value, detailId)),
    onSubmit: () =>
        dispatch(onSubmit(ownProps.id)).then(res => {
            if(res.ok) {
                dispatch(tableSearch({
                    pageIndex: PAGE.index
                }));
                ownProps.history.push(routes.query.url());
            }
            return res.ok;
        }),
    onCancel: () => {
        ownProps.history.push(routes.query.url());
    },
    onUmount: () => dispatch(clearData()),
    onClickCopyDetail: id => dispatch(onClickCopyDetail(id)),
    onClickAddDetail: () => dispatch(onClickAddDetail()),
    onColseTab: id => dispatch(deleteDetail(id)),
    onSelectDealer: data => dispatch(selectData(data))
});

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(injectIntl(Add));
